//
//  HeadImgViewController.m
//  marrymarry
//
//  Created by lsj on 16/9/9.
//  Copyright © 2016年 cf. All rights reserved.
//
static NSString * headImgCellID = @"HeadImgTableViewCell";
#import "HeadImgViewController.h"
#import "HeadImgTableViewCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
@interface HeadImgViewController ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    BOOL _isTopImg;
    NSString * _top_img_homeStr;
    NSString * _main_img_homeStr;
    
    NSString * _headimgPath;
    NSString * _faceimgPath;
    
    UIImage * _headImg;
    UIImage * _faceImg;
    NSMutableArray * _myPicArry;
    NSDictionary * headImgDic;
    NSDictionary * faceImgDic;
    
    NSMutableDictionary * _myNewBigDic;
    
    NSMutableDictionary * _myCacardDic;
    NSMutableDictionary * _myUserDic;
}
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (strong,nonatomic) UIImageView * mainImgView;
@property (strong,nonatomic) NSDictionary * myBigDic;
@property (strong,nonatomic) CFinfoModel * model;
@end

@implementation HeadImgViewController
-(UIImageView *)mainImgView
{
    if (!_mainImgView) {
        _mainImgView = [UIImageView new];
        _mainImgView.frame = CGRectMake(0,0,ScreenWidth,ScreenHeight-64-10-100-10-50-10);
    }
    return _mainImgView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    headImgDic = [NSDictionary new];
    faceImgDic = [NSDictionary new];
    self.myBigDic = [NSDictionary new];
    _myNewBigDic = [NSMutableDictionary new];
    self.model = [CFinfoModel new];
    _myPicArry  = [NSMutableArray new];
    _myCacardDic = [NSMutableDictionary new];
    _myUserDic = [NSMutableDictionary new];
     _top_img_homeStr = [NSString stringWithFormat:@"headIMG2.jpg"];
      _main_img_homeStr= [NSString stringWithFormat:@"mainIMG2.jpg"];
    self.view.backgroundColor = RGB(245, 245, 247);
    self.myTableView.backgroundColor = RGB(240, 239, 244);
    // Do any additional setup after loading the view.
    
    self.myBigDic = [Tools getValueFromNSUserDefaultsByKey:MY_BIGGEST_INFO_DIC];
    
    [self initNav];
    [self setMyTableViewFootView];
}



#pragma mark ------- 设置导航栏
-(void)initNav
{
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    
    UILabel * titleLable = [UILabel new];
    titleLable.frame = CGRectMake( 0, 20,ScreenWidth,44);
    titleLable.backgroundColor = RGB(245, 245, 247);
    titleLable.text = @"头像和主页封面";
    titleLable.font = [UIFont systemFontOfSize:18];
    titleLable.textColor = [UIColor blackColor];
    titleLable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLable];
    UIButton * finishBtn = [UIButton new];
    finishBtn.frame = CGRectMake(ScreenWidth-60,22,40,40);
    [finishBtn setTitleColor:RGB(0, 230, 196) forState:UIControlStateNormal];
    [finishBtn setTitle:@"完成" forState:UIControlStateNormal];
    [finishBtn addTarget:self action:@selector(goBacktoPinfoVC) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:finishBtn];
    UIImageView *leftView = [[UIImageView alloc]initWithFrame:CGRectMake(20,34, 20, 20)];
    leftView.image = [UIImage imageNamed:@"back-arrow"];
    leftView.userInteractionEnabled = YES;
    leftView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:leftView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(back)];
    [leftView addGestureRecognizer:tap];

}

-(void)setMyTableViewFootView
{
    
    if (self.myBigDic[@"idcard"][@"facePhoto"]) {
        [self.mainImgView setImageWithURL:[NSURL URLWithString:self.myBigDic[@"idcard"][@"facePhoto"]]];
    }
    self.myTableView.tableFooterView = self.mainImgView;
}

/**返回**/
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)goBacktoPinfoVC
{
    if ([self isFileExist:_top_img_homeStr] && [self isFileExist:_main_img_homeStr])
    {
        NSLog(@"点击了完成");
        
        NSData * headData = [NSData dataWithContentsOfFile:_headimgPath];
        _headImg = [UIImage imageWithData:headData];
        NSData *mainData = [NSData dataWithContentsOfFile:_faceimgPath];
        _faceImg = [UIImage imageWithData:mainData];
        
        headImgDic = @{@"imgname":@"headimg",@"pic":_headImg};
        faceImgDic = @{@"imgname":@"faceimg",@"pic":_faceImg};
        [_myPicArry addObject:headImgDic];
        [_myPicArry addObject:faceImgDic];
        
        [self requestTheNetWith:_myPicArry andURL:UPDATEMYPIC_URL andDic:@{@"id":[Tools getValueFromNSUserDefaultsByKey:USERID]}];


       
    }
    
    
}
#pragma mark ------- 判断是否添加了认证图片
//判断文件是否已经在沙盒中已经存在？
-(BOOL) isFileExist:(NSString *)fileName
{
    
    NSString *filePath =fileName;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    NSLog(@" 2----- documentsDirectory ==== %@",documentsDirectory);
    NSString * homePath =[documentsDirectory stringByAppendingPathComponent:filePath];

    BOOL result = [fileManager fileExistsAtPath:homePath];
    
    if(result)
    {
        NSLog(@"已存储");
        if ([fileName rangeOfString:@"head"].location!= NSNotFound ) {
            [Tools syncNSUserDeafaultsByKey:HEAD_PIC withValue:_top_img_homeStr];
            _headimgPath = homePath;
                       
        }else if ([fileName rangeOfString:@"main"].location!= NSNotFound)
        {
            [Tools syncNSUserDeafaultsByKey:PERSON_PIC withValue:_main_img_homeStr];
            _faceimgPath = homePath;
           
           

        }
    }
    else
    {
        if ([fileName rangeOfString:@"head"].location!= NSNotFound ) {
            [SVProgressHUD showErrorWithStatus:@"请上传头像"];
        }
        else if([fileName rangeOfString:@"main"].location!= NSNotFound)
        {
            [SVProgressHUD showErrorWithStatus:@"请上传个人形象照"];
        }else
        {
            [SVProgressHUD showErrorWithStatus:@"请上传照片"];
        }
    }
    return result;
}


-(void)goSetImg
{
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil                                                                             message: nil                                                                       preferredStyle:UIAlertControllerStyleActionSheet];
    //添加Button
    [alertController addAction: [UIAlertAction actionWithTitle: @"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        //处理点击拍照
        [self gochoseImgWithCarmeraOrLibrary:YES];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"从相册选取" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        //处理点击从相册选取
        [self gochoseImgWithCarmeraOrLibrary:NO];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    
    [self presentViewController: alertController animated: YES completion: nil];
}

-(void)gochoseImgWithCarmeraOrLibrary:(BOOL)isCarmra
{
    //读取图片的控制器
    UIImagePickerController *pick = [[UIImagePickerController alloc]init];
    
    //设置代理
    pick.delegate = self;
    
    //相片来源
    //UIImagePickerControllerSourceTypePhotoLibrary, 所有图片
    //UIImagePickerControllerSourceTypeCamera,       摄像头(模拟器会崩溃)
    //UIImagePickerControllerSourceTypeSavedPhotosAlbum 相册
    
    //判断当前设备是模拟器还是真机
    //模拟器
    if (isCarmra)
    {
        pick.sourceType = UIImagePickerControllerSourceTypeCamera;
    }else
    {
        pick.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
    }
    
    //是否允许对选择的图片进行编辑
    pick.allowsEditing = YES;
    
    //推出图片选择器
    [self presentViewController:pick animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
//选择图片的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
 
    
    NSLog(@"info==%@",info);
    if (_isTopImg)
    {

        //取到完整图片显示
        UIImageView * headImgView =(UIImageView *)[self.view viewWithTag:1001];
        
        headImgView.image = info[@"UIImagePickerControllerOriginalImage"];
        
        //让图片不失真,但是会超出边界
        headImgView.contentMode = UIViewContentModeScaleAspectFit;
        
        //UIImagePNGRepresentation     将image转成PNG格式二进制数据
        //UIImageJPEGRepresentation    将image转成JPG格式二进制数据
        //将UIImage转NSdata
        
        //第一个参数   需要转化的image对象
        //第二个参数   压缩比例
//        NSData *data1 = UIImageJPEGRepresentation(info[@"UIImagePickerControllerEditedImage"], 0.00001);
        
        NSData *data2 = UIImageJPEGRepresentation(info[@"UIImagePickerControllerEditedImage"], 1.0);
        
        //取到沙盒路径
        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * documentsDirectory = [paths objectAtIndex:0];
        NSLog(@" 1----- documentsDirectory ==== %@",documentsDirectory);
        //    [data1 writeToFile:[homePath stringByAppendingString:@"/Documents/left1.jpg"] atomically:YES];
       
        [data2 writeToFile:[documentsDirectory stringByAppendingPathComponent:_top_img_homeStr] atomically:NO];
        _headimgPath = [documentsDirectory stringByAppendingString:_top_img_homeStr];

        
        
    }
    else
    {

        //取到完整图片显示
        self.mainImgView.image = info[@"UIImagePickerControllerOriginalImage"];
        
        //让图片不失真,但是会超出边界
        self.mainImgView.contentMode = UIViewContentModeScaleAspectFit;
        
        //UIImagePNGRepresentation     将image转成PNG格式二进制数据
        //UIImageJPEGRepresentation    将image转成JPG格式二进制数据
        //将UIImage转NSdata
        
        //第一个参数   需要转化的image对象
        //第二个参数   压缩比例
//        NSData *data1 = UIImageJPEGRepresentation(info[@"UIImagePickerControllerEditedImage"], 0.00001);
        
        NSData *data2 = UIImageJPEGRepresentation(info[@"UIImagePickerControllerEditedImage"], 1.0);
        

        
        //取到沙盒路径
        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * documentsDirectory = [paths objectAtIndex:0];
        NSLog(@" 1----- documentsDirectory ==== %@",documentsDirectory);
        //    [data1 writeToFile:[homePath stringByAppendingString:@"/Documents/left1.jpg"] atomically:YES];
      
        [data2 writeToFile:[documentsDirectory stringByAppendingPathComponent:_main_img_homeStr] atomically:NO];
        
        _faceimgPath = [documentsDirectory stringByAppendingString:_main_img_homeStr];
     
    }
    
#if 0
    //NSString 和 NSData 互转
    NSString *string = [[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding];
    
    NSData *data = [@"hello" dataUsingEncoding:NSUTF8StringEncoding];
#endif
    
    
    //退出图片选择器
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark -----UITableViewDataSource,UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    HeadImgTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:headImgCellID];
    if (!cell) {
        cell = [[HeadImgTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:headImgCellID];
        
    }
    [cell reloadWithTheIndexPath:indexPath];
    if (indexPath.section == 0) {
        if (self.myBigDic[@"user"][@"headimg"]) {
            [cell.headImgView setImageWithURL:[NSURL URLWithString:self.myBigDic[@"user"][@"headimg"]]];
        }else{
        
        NSData * headData = [NSData dataWithContentsOfFile:_top_img_homeStr];
        [cell.headImgView setImage:[UIImage imageWithData:headData]];
        }
        cell.headImgView.tag = 1001;
    }
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 100;
    }else{
        return 50;
    }
  
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
        return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    [self goSetImgWithIndexPath:indexPath];
    
    
}


-(void)goSetImgWithIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        _isTopImg = YES;
    }else if (indexPath.section == 1)
    {
        _isTopImg = NO;
    }
    [self goSetImg];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark --------------网络请求
-(void)requestTheNetWith:(NSArray *)myRequestArry andURL:(NSString *)myurl andDic:(NSDictionary *)myDic;
{
    if (myRequestArry.count>0) {
        [[LJFNetworkingManager shareManager] POST:myurl upLoadImages:myRequestArry parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
            NSLog(@"returnData ==== %@",returnData);
            NSDictionary * picDic =[NSDictionary new];
            picDic =[self.model saveTheNetHFPicDic:returnData];
            _myNewBigDic = [NSMutableDictionary dictionaryWithDictionary:self.myBigDic];
            _myCacardDic = [NSMutableDictionary dictionaryWithDictionary:_myNewBigDic[@"idcard"]];
            _myUserDic = [NSMutableDictionary dictionaryWithDictionary:_myNewBigDic[@"user"]];
            [_myCacardDic setObject:picDic[@"faceImg"] forKey:FACEPHOTO];
            [_myUserDic setObject:picDic[@"headImg"] forKey:HEADPHOTO];
            [_myNewBigDic setObject:_myCacardDic forKey:@"idcard"];
            [_myNewBigDic setObject:_myUserDic forKey:@"user"];
            NSDictionary * dicNewBig = [NSDictionary dictionaryWithDictionary:_myNewBigDic];
            [self.model saveTheBiggestDic:dicNewBig];
        [self.navigationController popViewControllerAnimated:YES];
        } failure:^(NSError *error) {
            NSLog(@"失败");
      
        } showHUD:self.view];
        [self.myTableView reloadData];
    }else
    {
        [[LJFNetworkingManager shareManager] POST:myurl parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
                      
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        } showHUD:self.view];
        
    }
    
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
